<template>
  <el-scrollbar view-style="max-height: 720px;">
    <div class="container-box" id="container-box">
      <el-row>
        <el-col :xl="14" :lg="14" :md="16" :sm="16" :xs="18">
          <el-form :model="orderForm" status-icon :rules="rules" ref="orderForm" label-width="100px">
            <el-form-item label="优惠金额：" prop="order_discount">
              <el-input-number v-model="orderForm.order_discount" :precision="2" :max="totalAmount"></el-input-number>
            </el-form-item>
            <el-form-item
              v-for="(product, index) in orderForm.products"
              :label="'产品' + (index+1) + ':'"
              :key="product.key"
              :prop="'products.' + index + '.value'"
            >
              <el-row :gutter="24">
                <el-col :span="20">
                  <el-row :gutter="24">
                    <el-col :span="6">
                      <el-select
                        v-model="orderForm.products[index].value"
                        @focus="handleClearProductOptions()"
                        clearable
                        filterable
                        allow-create
                        remote
                        placeholder="请输入关键词"
                        :remote-method="remoteProduct"
                        :loading="loading">
                        <el-option
                          v-for="(item,index) in productOptions"
                          :key="index"
                          :value="item.label">
                        </el-option>
                      </el-select>
                    </el-col>
                    <el-col :span="9">
                      <span class="cost">费用：</span>
                      <el-input-number v-model="orderForm.products[index].amount" :min="0" :precision="2" label="描述文字" @change="handleChangeAmount"></el-input-number>
                    </el-col>
                    <el-col :span="9">
                      <span class="cost">数量：</span>
                      <el-input-number v-model="orderForm.products[index].quantity" :min="0" label="描述文字" @change="handleChangeAmount"></el-input-number>
                    </el-col>
                  </el-row>
                </el-col>
                <el-col :span="4" v-if="index !== 0">
                  <el-button @click.prevent="handleDeleteProduct(product)">删除</el-button>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label=" ">
              <el-button icon="el-icon-circle-plus-outline" @click="handleAddProduct()">添加产品</el-button>
            </el-form-item>
            <el-form-item label="状态：" prop="active">
              <el-select v-model="orderForm.active" placeholder="请选择订单状态">
                <el-option label="可用" value="1"></el-option>
                <el-option label="禁用" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm('orderForm')">立即更新</el-button>
              <el-button @click="resetForm()">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
  </el-scrollbar>
</template>

<script>
import { timestampToDate } from "../../assets/js/utils";

export default {
  data() {
    return {
      orderForm: {
        order_discount: 0,
        products: [
          {
            value: "",
            amount: 0,
            quantity: 1
          }
        ],
        active: ""
      },
      productOptions: [],
      products: [],
      productList: [],
      orderData: [],
      totalAmount: 0,
      prevAmount: 0,
      loading: false,
      params: {
        "access-token": window.localStorage.getItem("token")
      },
      rules: {
        active: [{ required: true, message: "请选择状态", trigger: "change" }]
      }
    };
  },
  mounted() {
    let token = window.localStorage.getItem("token");

    this.axios
      .get("products/data?access-token=" + token, { params: this.params })
      .then(res => {
        this.products = res.data.data ? res.data.data.products : [];

        this.productList = this.products.map(item => {
          return { value: item.product_id, label: item.product_name };
        });
      });
  },
  created: function() {
    this.getOrderPorduct();
  },
  methods: {
    getOrderPorduct: function() {
      let order_id = this.$route.params.id;

      this.axios
        .get("orders/" + order_id, { params: this.params })
        .then(res => {
          let data = res.data.data.order;
          this.totalAmount = parseFloat(data.order_amount);
          this.orderForm = {
            order_id: data.order_id,
            order_discount: data.order_discount,
            products: data.products,
            active: data.active
          };

          this.orderData = JSON.parse(JSON.stringify(this.orderForm));

          this.resetForm("orderForm");
        });
    },
    remoteProduct(query) {
      if (query !== "") {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.productOptions = this.productList.filter(item => {
            return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
          });
        }, 200);
        this.productOptions = this.productList.filter(item => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
      } else {
        this.productOptions = [];
      }
    },
    handleClearProductOptions() {
      this.productOptions = [];
    },
    handleAddProduct() {
      this.orderForm.products.push({
        value: "",
        amount: 0,
        quantity: 1,
        key: Date.now()
      });
    },
    handleDeleteProduct(item) {
      var index = this.orderForm.products.indexOf(item);
      if (index !== -1) {
        this.orderForm.products.splice(index, 1);
      }
    },
    handleChangeAmount(value) {
      let totalAmount = 0;
      this.orderForm.products.map(item => {
        totalAmount = totalAmount + item.amount;
      });
      this.totalAmount = totalAmount;
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let token = window.localStorage.getItem("token");
          this.axios
            .patch(
              "orders/" +
                this.orderForm.order_id +
                "?access-token=" +
                window.localStorage.getItem("token"),
              this.orderForm
            )
            .then(res => {
              if (res.data.code === "1000") {
                this.$message({
                  type: "success",
                  message: "更新成功!"
                });

                this.$refs.orderForm.clearValidate();
              } else {
                this.$message({
                  type: "error",
                  message: res.data.message
                });
              }
            });
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.orderForm = JSON.parse(JSON.stringify(this.orderData));
    }
  }
};
</script>

<style lang="scss" scoped>
.container-box {
  overflow: hidden;
}

.el-row {
  margin-left: 0 !important;
}

.el-col {
  &:first-child {
    padding-left: 0 !important;
  }
}
</style>
